package com.cjm.nio.ifeve;

import java.net.Socket;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * <a href="http://ifeve.com/selectors/">Selector</a>
 * 1. 为什么使用Selector（）
 * 2。 Selector的创建
 * 3。 向Selector注册通道
 * 4。 SelectionKey
 * 5。 通过Selector选择通道
 * 6。 wakeUP
 *  某个线程调用select()方法后阻塞了， 即使没有通道已经就绪， 也有办法让其select()方法返回， 只要让其它线程在第一个线程调用select方法的那个对象上调用select.wakeup方法即可， 阻塞在select方法上的线程会立马返回
 * 7。 close
 * 8。 完整的示例
 */
public class SelectorLean {
    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_READ);
        int interestOps = selectionKey.interestOps();
        int readOps = selectionKey.readyOps();
        boolean acceptable = selectionKey.isAcceptable();
        boolean connectable = selectionKey.isConnectable();
        boolean readable = selectionKey.isReadable();
        boolean writable = selectionKey.isWritable();
        SelectableChannel channel1 = selectionKey.channel();
        Selector selector1 = selectionKey.selector();
        selectionKey.attach(new Object());
        Object attachment = selectionKey.attachment();

        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
        while (keyIterator.hasNext()) {
            SelectionKey next = keyIterator.next();
            if (next.isAcceptable()) {

            } else if (next.isReadable()) {

            } else if (next.isWritable()) {

            }
            keyIterator.remove();
        }
        System.err.println("OK");

        int select = selector.select();
        Selector wakeup = selector.wakeup();
    }
}
